from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from config import dict_config,Config
from flask_wtf import  csrf,CSRFProtect

'''
设置系统日志
'''
import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(level=logging.DEBUG)
file_log_handler = RotatingFileHandler('logs/log',maxBytes=1024*1024*100,backupCount=10)
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
file_log_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_log_handler)

'''
创建redis数据库实例，用以存储图片验证码或短信验证码
'''
redis_store = StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT,decode_responses=True)

db = SQLAlchemy()

def create_app(mode):
    app = Flask(__name__)
    app.config.from_object(dict_config[mode])

    Session(app)
    db.init_app(app)

    CSRFProtect(app)
    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        response.set_cookie('csrf_token',csrf_token)
        return response

    from info.modules.home import home_blue
    app.register_blueprint(home_blue)
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from info.modules.profile import profile_blue
    app.register_blueprint(profile_blue)
    from info.modules.order import order_blue
    app.register_blueprint(order_blue)


    # houses蓝图
    from  info.modules.houses import houses_blue
    app.register_blueprint(houses_blue)

    return app

